#!/usr/bin/env python
# coding=utf-8
# @FileName :crud.py
# @Time     :2023/4/10 18:51
# @Author   :ZXC
# @Desc     :
import time
from typing import Tuple, List

from sqlalchemy import text
from sqlalchemy.exc import ResourceClosedError
from sqlalchemy.ext.asyncio import async_sessionmaker


async def execute(ss: async_sessionmaker, sql: str) -> Tuple | List:
    """
    执行
    :param ss: 数据库连接会话对象
    :param sql: sql
    :return:
    """
    row_count = 0
    async with ss() as s:
        async with s.begin():
            try:
                start = time.perf_counter()
                result = await s.execute(text(sql))
                cost = time.perf_counter() - start
                row_count = result.rowcount
                ans = result.mappings().all()
                return ans, int(cost * 1000)  # 结果和耗时
            except ResourceClosedError:
                # 说明是update或其他语句
                return [{"rowCount": row_count}]
            except Exception as e:
                print(f"查询数据库配置失败, error: {e}")
                raise Exception(f"执行sql失败: {e}")
